package com.easy.api.factory.file.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.easy.api.annotation.FileModelGenerate;
import com.easy.api.utils.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;

import javax.swing.filechooser.FileSystemView;
import java.io.File;
import java.io.FileNotFoundException;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * @Author liuyuan
 * @Date 2020/5/15 7:30 下午
 * @Version 1.0
 */
public abstract class HeaderFileTemplate {

    public Map<String, Object> templateMap;

    public FileModelGenerate fileModelGenerate;

    public Method method;

    public Object[] args;

    public void buildHeaderTemplate(FileModelGenerate fileModelGenerate,Method method, Object[] args) {
       // this.templateMap = ObjectUtils.toMap(args[0]);
        this.templateMap = JSONObject.parseObject(JSON.toJSONString(args[0]));
        this.fileModelGenerate = fileModelGenerate;;
        this.method = method;
        this.args = args;
    }

    public abstract void generateFile() throws FileNotFoundException;

    /**
     * 获取文件目录
     * */
    public String getFileName(){
        FileModelGenerate fileModelGenerate = this.fileModelGenerate;
        String outFilePath = fileModelGenerate.outFilePath();
        if(StringUtils.isBlank(outFilePath)){
            FileSystemView fsv = FileSystemView.getFileSystemView();
            File file = fsv.getHomeDirectory();
            if( file.getPath().contains("Desktop")){
                outFilePath = file.getPath()+"/";
            }else {
                outFilePath = file.getPath()+"/Desktop/";
            }
        }
        return outFilePath + fileModelGenerate.fileName() +"."+fileModelGenerate.type().getCode();
    }


    public String render(String templatePath,String fileName, Map<String,Object> params){
        //构造模板引擎
        ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
        resolver.setPrefix(templatePath);//模板所在目录，相对于当前classloader的classpath。
        resolver.setSuffix(".html");//模板文件后缀
        TemplateEngine templateEngine = new TemplateEngine();
        templateEngine.setTemplateResolver(resolver);
        Context context = new Context();
        params.forEach((k,v)->{
            context.setVariable(k,v);
        });

        return templateEngine.process(this.fileModelGenerate.templateName(),context);
    }


}
